package com.yuma.completablefuture;

import java.util.concurrent.*;

public class CompletableFutureDemo1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

        // -----------------创建异步编排对象-------
        // 1.void runAsync(Runnable, Executor);
        // 1.void runAsync(Runnable);
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            System.out.println("runAsync ....");
        },threadPool);

        System.out.println("main over");
        System.out.println("future.get() = " + future.get());


        // 2.T supplyAsync(Supplier<U>, Executor);
        // 2.T supplyAsync(Supplier<U>);
        CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("supplyAsync....");
            int i = 1/0;
            return "hello";
        },threadPool)    // 当异步编排的任务结束了，执行whenComplete
        .whenCompleteAsync((t,u)->{  // t 是编排任务的返回值“hello"， u当有异常时候的异常对象
            System.out.println("supplyAsync whenComplete: " + t);
            System.out.println("supplyAsync whenComplete exception : " + u);
        })    // 当异步编排出现异常了
        .exceptionally(e->{  // e代表异常对象
            System.out.println("supplyAsync execptionally exception : " + e.getMessage());
            // 如果出现异常，就不会返回代码26行的“hello”
            return "world";
        });

        System.out.println("stringCompletableFuture.get() = " + stringCompletableFuture.get());
        threadPool.shutdown();
    }
}
